package com.sugar.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class BaseController {

    @InitBinder
    protected void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class,new MyDateEditor());
        // java自带将Double转为字符串的编辑器
        //binder.registerCustomEditor(Double.class,new DoubleEditor());
        // 自定义将web传入String转为Double,后端返回Double转为String
        binder.registerCustomEditor(Double.class,new MyDoubleEditor());
        // java自带将Integer转为字符串的编辑器
        //binder.registerCustomEditor(Double.class,new IntegerEditor());
        // 自定义将web传入String转为Integer,后端返回Integer转为String
        binder.registerCustomEditor(Integer.class,new MyIntegerEditor());

        binder.setDisallowedFields("address");
        log.info("设置值");
    }

    protected class MyDateEditor extends PropertyEditorSupport{
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = format.parse(text);
            } catch (ParseException e) {
                format = new SimpleDateFormat("yy-MM-dd");
                try {
                    format.parse(text);
                } catch (ParseException ex) {
                    log.error("日期格式转换失败:{}",ex);
                }
            }
            setValue(date);
        }
    }

    protected class MyDoubleEditor extends PropertiesEditor{
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Double.parseDouble((text==null||text.equals(""))?"0":text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    protected class MyIntegerEditor extends PropertyEditorSupport{
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Integer.parseInt((text==null||text.equals(""))?"0":text));
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

}
